package com.cloud.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.core.domain.Ztree;
import com.cloud.admin.common.exception.BusinessException;
import com.cloud.admin.common.utils.StringUtils;
import com.cloud.admin.mapper.SysDeptMapper;
import com.cloud.admin.model.entity.SysDept;
import com.cloud.admin.model.entity.SysRole;
import com.cloud.admin.service.SysDeptService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门表
 *
 * @author douhaichao code generator
 * @date 2019-07-09 10:27:13
 */
@Service
@AllArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public SysDept selectOne(SysDept req) {
        QueryWrapper queryWrapper = new QueryWrapper<SysDept>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Ztree> selectDeptTree(SysDept dept) {
        List<SysDept> deptList = baseMapper.selectDeptList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    @Override
    public List<Ztree> roleDeptTreeData(SysRole role) {
        Integer roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDept> deptList = baseMapper.selectDeptList(new SysDept());
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleDeptList = baseMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    @Override
    public boolean checkDeptExistUser(Integer deptId) {
        return baseMapper.selectDeptExistUser(deptId) > 0;
    }

    @Override
    public int insertDept(SysDept dept) {
        SysDept info = baseMapper.selectById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new BusinessException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return baseMapper.insert(dept);
    }

    @Override
    @Transactional
    public int updateDept(SysDept dept) {
        SysDept newParentDept = baseMapper.selectById(dept.getParentId());
        SysDept oldDept = baseMapper.selectById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = baseMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Integer deptId = StringUtils.isNull(dept.getDeptId()) ? -1 : dept.getDeptId();
        SysDept info = baseMapper.selectDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId() != deptId) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    @Override
    public SysDept getDeptInfo(Integer deptId) {
        return baseMapper.getDeptInfo(deptId);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Integer deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = baseMapper.selectList(new QueryWrapper<SysDept>().eq("parent_id", deptId));
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            baseMapper.updateDeptChildren(children);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = baseMapper.selectById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        baseMapper.updateDeptStatus(dept);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList) {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList     部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (SysDept dept : deptList) {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setPId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck) {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<SysDept> selectAll(SysDept req) {
        QueryWrapper<SysDept> queryWrapper = new QueryWrapper<SysDept>();
        if (!(req.getDeptName() == null || req.getDeptName().isEmpty())) {
            queryWrapper.like("dept_name", req.getDeptName());
        }
        if (!(req.getStatus() == null || req.getStatus().isEmpty())) {
            queryWrapper.eq("status", req.getStatus());
        }
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<SysDept> selectPage(Page page, SysDept req) {
        IPage<SysDept> list = baseMapper.selectPage(
                page,
                new QueryWrapper<SysDept>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<SysDept> selectPageByLike(Page page, SysDept req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getDeptId()) {
            queryWrapper.eq("dept_id", req.getDeptId());
        }

        if (null != req.getParentId()) {
            queryWrapper.eq("parent_id", req.getParentId());
        }

        if (!StrUtil.isEmpty(req.getAncestors())) {
            queryWrapper.like("ancestors", req.getAncestors());
        }

        if (!StrUtil.isEmpty(req.getDeptName())) {
            queryWrapper.like("dept_name", req.getDeptName());
        }

        if (null != req.getOrderNum()) {
            queryWrapper.eq("order_num", req.getOrderNum());
        }

        if (!StrUtil.isEmpty(req.getLeader())) {
            queryWrapper.like("leader", req.getLeader());
        }

        if (!StrUtil.isEmpty(req.getPhone())) {
            queryWrapper.like("phone", req.getPhone());
        }

        if (!StrUtil.isEmpty(req.getEmail())) {
            queryWrapper.like("email", req.getEmail());
        }

        if (!StrUtil.isEmpty(req.getStatus())) {
            queryWrapper.like("status", req.getStatus());
        }

        if (!StrUtil.isEmpty(req.getDelFlag())) {
            queryWrapper.like("del_flag", req.getDelFlag());
        }

        if (!StrUtil.isEmpty(req.getCreateBy())) {
            queryWrapper.like("create_by", req.getCreateBy());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (!StrUtil.isEmpty(req.getUpdateBy())) {
            queryWrapper.like("update_by", req.getUpdateBy());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }
        IPage<SysDept> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(SysDept req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

}
